import {MD5} from './md5'
import fetchJsonp from 'fetch-jsonp'
import {getTranslate} from "@/api";

// interface Options {
//     method: string
//     url: string
//     data: object
//     dataType: string
// }

class Translate {
    /*  通用配置 */
    URL = 'http://fanyi-api.baidu.com/api/trans/vip/translate'
    Appid = '20230524001687955'
    AppKey = 'F6CVuzMDOrJ0QXf_GFVQ'
    init = false

    /*-------------------------------------------------*/

    /* jsonp -- 支持跨域 */
    jsonp(option?: any) {
        const opt = option || {};
        const Salt = Date.now()
        let newTxt = opt.text
        newTxt = newTxt.replaceAll('\n', '');
        /* eslint-disable-next-line */
        newTxt = newTxt.replace(/\ +/g, "");
        let Sign = this.Appid + newTxt + Salt + this.AppKey;
        Sign = `${MD5(Sign)}`
        opt.method = opt.method || 'POST';
        opt.url = opt.url || this.URL;
        opt.data = opt.data || {
            q: opt.text || '',
            appid: this.Appid,
            salt: Salt,
            from: 'auto',
            to: opt.lang || 'en',
            sign: Sign
        };
        opt.dataType = opt.dataType || 'JSONP';
        const params: any = [];
        Object.keys(opt.data).forEach((key: any, index: number) => {
            const cur = Object.values(opt.data)[index]
            params.push(key + '=' + cur);
        })
        const postData = params.join('&');
        if (opt.dataType === 'JSONP') {
            (async () => {
                try {
                    if (process.env.NODE_ENV === 'production') {
                        const res = await getTranslate(`${opt.url}?${postData}`)
                        const result: object = res.data || {}
                        window.fn(result)
                    } else {
                        await fetchJsonp(`${opt.url}?${postData}`, {
                            jsonpCallbackFunction: 'fn',
                            timeout: 6000,
                        })
                    }

                } catch (e) {
                    console.log(e)
                }
            })()
        }
    }

    constructor(text?: any) {
        this.init = text || true
    }
}

const translate = (text: any, lang?: any) => {
    // data = 'q='+ transText + '&from=auto&to=' +lang +'&appid=' +appid+ '&salt='+ salt + '&sign=' +sign;
    return new Promise(resolve => {
        // Lang: string, text: any
        if (!text?.length) {
            console.log('值不能为空')
            return
        }
        // 正则匹配非法字符
        /* eslint-disable-next-line */
        const pat = /[^a-zA-Z0-9\_\s*\u4e00-\u9fa5]/g
        let query: any = text
        if (pat.test(text)) {
            query = text.replace(pat, '');
        }
        const TranslateInstance = new Translate()
        TranslateInstance.jsonp({
            text: query,
            lang: lang
        })
        window.fn = (str: any) => {
            resolve(str)
        }
    })
}
export default translate
